package ro.asterix;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
//import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.asterix.business.BusinessValidationException;
import ro.asterix.data.Oaspete;
import ro.asterix.factory_pattern.OaspeteManagerFactory;
import ro.asterix.interfaces.OaspeteManager;

@SuppressWarnings("serial")
public class ServletExampleServlet extends HttpServlet {

	/* Decalring a Logger instance */
	private static final Logger log = Logger
			.getLogger(ServletExampleServlet.class.getName());

	/**
	 * Pentru metoda POST preluam parametrii si procesam datele returnand un
	 * document HTML
	 * 
	 * @author ETATARU version 1.0 Draft
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/* Setting the MIME type for the servlet/HTML document */
		resp.setContentType("text/html");

		/* Getting an OaspeteManager instance. */
		OaspeteManager manager = OaspeteManagerFactory.getOaspeteManager();
		/* Luam parametrii din formular. */
		String name = req.getParameter("name");
		String surname = req.getParameter("surname");
		/* Punem un timestamp. */
		Date data = new Date();
		/* Creating the Java Bean object [Model]. */
		Oaspete oaspete = new Oaspete(name, surname, data);
		/* Using the OaspeteManager - store the new object. */
		try {
			manager.save(oaspete);
		} catch (BusinessValidationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/* Logging the new Oaspete. */
		log.info("Avem un oaspete: " + oaspete.toString());

		/* Get a reference to writer. */
		PrintWriter out = resp.getWriter();
		/* Send the HTML response. */
		out.println(generateHtml().toString());
		/* Closing the out stream. */
		out.close();
	}

	private StringBuilder generateHtml() {

		// Cream un StringBuilder care tine continutul HTML
		StringBuilder sb = new StringBuilder("");

		sb.append("<html><head>")
				.append("<title> Exemplu de utilizare dataStore in servlet!</title>")
				.append("</head>").append("<body>");

		// Creare raspunsului HTML
		sb.append("<div>");
		sb.append("<form action=\"/servletexample\" method=\"post\">")
				.append("<fieldset> <legend> Guest Check-in</legend> "
						+ "First Name: <input type=\"text\" name=\"surname\">")
				.append("Last Name: <input type=\"text\" name=\"name\">")
				.append("<input type=\"submit\" value=\"Submit\" />")
				.append("</form>");
		sb.append("</div>");
		/* Lista de oaspeti! */
		/* Refresh the list. */
		List<Oaspete> oaspeti;
		OaspeteManager manager = OaspeteManagerFactory.getOaspeteManager();
		oaspeti = manager.getOaspeti();
		
		if (oaspeti == null) {
			sb.append("<p> Lista este goala!</p>").append("</div>");
		} else {
			sb.append("<p> Lista are ").append(oaspeti.size())
					.append(" elemente!</p>").append("<div><ol>").append("");
		}

		/* Creare elemente lista. */
		if (oaspeti != null) {
			for (Oaspete oaspete : oaspeti) {

				sb.append("<li>").append(oaspete.getSurname()).append(" ")
						.append(oaspete.getName()).append(" : at( ")
						.append(oaspete.getCheckIn()).append(")</li>");
			}
		}

		/* Close HTML page. */
		sb.append("</ol></div>").append("</body\"></html>");

		return sb;
	}

	/**
	 * Pentru metoda GET returnam un formular pentru introducerea datelor
	 * 
	 */
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// setam tipul MIME pentru antetul HTTP
		resp.setContentType("text/html");
		// obtinem o referinta la fluxul de iesire
		PrintWriter out = resp.getWriter();
		// trimitem raspunsul HTML
		out.println(generateHtml().toString());
		// inchidem fluxul de iesire
		out.close();
	}
}